package com.zzhrtech.wgzx_cityzen.ui.task;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Text;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.GsonRequest;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.squareup.picasso.Picasso;
import com.zzhrtech.WgzxApplication;
import com.zzhrtech.wgzx_cityzen.BaseActivity;
import com.zzhrtech.wgzx_cityzen.Constans;
import com.zzhrtech.wgzx_cityzen.R;
import com.zzhrtech.wgzx_cityzen.beans.disease.AreaListBean;
import com.zzhrtech.wgzx_cityzen.beans.disease.CateContentBean;
import com.zzhrtech.wgzx_cityzen.beans.disease.CateInfoBean;
import com.zzhrtech.wgzx_cityzen.beans.disease.CateListBean;
import com.zzhrtech.wgzx_cityzen.beans.disease.RoleListBean;
import com.zzhrtech.wgzx_cityzen.beans.task.BaseBean;
import com.zzhrtech.wgzx_cityzen.beans.task.TaskDetailBean;
import com.zzhrtech.wgzx_cityzen.beans.task.TaskFilterBean;
import com.zzhrtech.wgzx_cityzen.beans.task.TaskReasonBean;
import com.zzhrtech.wgzx_cityzen.ui.disease.ImagePickActivity;
import com.zzhrtech.wgzx_cityzen.view.CustomProgress;

import org.angmarch.views.NiceSpinner;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TaskDetailActivity extends BaseActivity implements GeocodeSearch.OnGeocodeSearchListener {

    private ViewGroup photoGroup;
    TextureMapView mMapView;
    AMap aMap;

    private TextView tv_type,tv_kind,tv_content,
                tv_address,tv_time,tv_name,tv_phone,tv_note;
    private String taskid;


    private Dialog proDialog;

    TextView tv_rizhi;


    private ArrayList<String> thImgList = new ArrayList<String>();
    private String mapPoint;
    private CardView card_qxreason;
    private TextView tv_qxreason;

    private ArrayList<String> fankuiImgList = new ArrayList<String>();
    private CardView card_fankui;
    private TextView tv_fkneirong;
    private LinearLayout layout_fankui;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_detail);

        mMapView = (TextureMapView) findViewById(R.id.map);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，实现地图生命周期管理
        mMapView.onCreate(savedInstanceState);
        toolbar.setNavigationIcon(R.mipmap.ic_close);
        taskid = getIntent().getStringExtra("taskid");

        proDialog = CustomProgress.show(this,true,null);
        initMap();

        initView();

        httpGetTask(taskid);
    }



    private void initView() {
        photoGroup = (ViewGroup) findViewById(R.id.selected_photos_container);

        tv_rizhi = (TextView) findViewById(R.id.tv_rizhi);

        tv_rizhi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(TaskDetailActivity.this,TaskRizhiActivity.class);
                intent.putExtra("taskid",taskid);
                intent.putExtra("now",getIntent().getStringExtra("now"));
                startActivity(intent);
            }
        });




        tv_type = (TextView) findViewById(R.id.tv_type);
        tv_kind = (TextView) findViewById(R.id.tv_kind);
        tv_content = (TextView) findViewById(R.id.tv_content);
        tv_address = (TextView) findViewById(R.id.tv_address);
        tv_time = (TextView) findViewById(R.id.tv_time);
        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_phone = (TextView) findViewById(R.id.tv_phone);
        tv_note = (TextView) findViewById(R.id.tv_note);
        card_qxreason = (CardView) findViewById(R.id.card_qxreason);
        tv_qxreason = (TextView) findViewById(R.id.tv_qxreason);
        card_fankui = (CardView) findViewById(R.id.card_fankui);
        tv_fkneirong = (TextView) findViewById(R.id.tv_fkneirong);
        layout_fankui = (LinearLayout) findViewById(R.id.layout_fankui);

        if (getIntent().getStringExtra("now").equals("已取消")){
            card_qxreason.setVisibility(View.VISIBLE);
            httpGetRizhi(taskid);
        }

    }


    private void showPic(final ArrayList<String> imageList) {
        //dip转换为sp
        int wdpx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics());
        int htpx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics());

        for (int i = 0;i < imageList.size();i++) {
            View imageHolder = LayoutInflater.from(this).inflate(R.layout.item_image, null);
            ImageView thumbnail = (ImageView) imageHolder.findViewById(R.id.media_image);
            final int currentPage = i;
            thumbnail.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Intent intent = new Intent(TaskDetailActivity.this,ImagePickActivity.class);
                    intent.putStringArrayListExtra("images",imageList);
                    intent.putExtra("current",currentPage);
                    intent.putExtra("channel","task");
                    startActivity(intent);
                }
            });

            Picasso.with(this)
                    .load(imageList.get(i))
                    .placeholder(R.mipmap.ic_placehoder)
                    .into(thumbnail);

            photoGroup.addView(imageHolder);
            thumbnail.setLayoutParams(new FrameLayout.LayoutParams(wdpx, htpx));
        }
    }

    /**
     * 初始化AMap对象
     */
    private void initMap() {
        if (aMap == null) {
            aMap = mMapView.getMap();

            aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
                @Override
                public void onMapClick(LatLng latLng) {
                    Intent intent = new Intent(TaskDetailActivity.this,TaskMapActivity.class);
                    intent.putExtra("point",mapPoint);
                    startActivity(intent);
                }
            });

            //更改可视区域

//            setUpMap();
        }
    }
    private void setUpMap(){

        GeocodeSearch geocoderSearch = new GeocodeSearch(this);
        geocoderSearch.setOnGeocodeSearchListener(this);
        //latLonPoint参数表示一个Latlng，第二参数表示范围多少米，GeocodeSearch.AMAP表示是国测局坐标系还是GPS原生坐标系
        LatLonPoint latLonPoint = new LatLonPoint(125.349219,43.893274);
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200,GeocodeSearch.AMAP);
        geocoderSearch.getFromLocationAsyn(query);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
    }
    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，实现地图生命周期管理
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {

    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {

            if (msg.what == 0){
                proDialog.dismiss();


                TaskDetailBean.Data data = (TaskDetailBean.Data) msg.obj;

                tv_type.setText(data.getDep_name());
                tv_kind.setText(data.getCat_name());
                tv_content.setText(data.getCi_name());
                tv_address.setText(data.getTask_address());
                tv_time.setText(data.getTask_date());
                tv_name.setText(data.getTask_name());
                tv_phone.setText(data.getTask_phone());
                tv_note.setText(data.getTask_detail());

                mapPoint = data.getTask_point();

                String[] lats = data.getTask_point().split(",");
//                Log.d("lat=======",Double.parseDouble(lats[0]) + "/" + Double.parseDouble(lats[1]) + "/" + data.getTask_point());
                LatLng latLng = new LatLng(Double.parseDouble(lats[1]),Double.parseDouble(lats[0]));

//                LatLng latLng = new LatLng(43.845005,125.41314);
                CameraUpdate update = CameraUpdateFactory.newCameraPosition(new CameraPosition(
                        latLng, 17, 30, 0));
                aMap.moveCamera(update);
                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.position(latLng);
                aMap.addMarker(markerOptions);

                if (data.getOneImgTh() != null){
                    thImgList.add(data.getOneImg());
                    if (data.getTwoImgTh() != null){
                        thImgList.add(data.getTwoImg());
                        if (data.getThreeImgTh() != null){
                            thImgList.add(data.getThreeImg());
                        }
                    }
                }


                if (data.getXiuOneImg() != null){
                    fankuiImgList.add(data.getXiuOneImg());
                    if (data.getXiuTwoImg() != null){
                        fankuiImgList.add(data.getXiuTwoImg());
                        if (data.getXiuThreeImg() != null){
                            fankuiImgList.add(data.getXiuThreeImg());
                        }
                    }
                }

                if (data.getFanneirong() != null) {
                    if (!data.getFanneirong().equals("")) {
                        card_fankui.setVisibility(View.VISIBLE);
                        tv_fkneirong.setText(data.getFanneirong());
                    }
                }

                if (fankuiImgList.size() > 0) {
                    showFankui(fankuiImgList);
                }

                showPic(thImgList);

            }else if (msg.what == 2){
                List<TaskFilterBean.Data> reasonList = (List<TaskFilterBean.Data>) msg.obj;
                for (int i = 0;i < reasonList.size();i++){
                    if (reasonList.get(i).getStatus().equals("已取消")) {
                        if (reasonList.get(i).getReason() == null){
                            tv_qxreason.setText("无");
                        }else {
                            tv_qxreason.setText(reasonList.get(i).getReason());
                        }

                        break;
                    }

                }
            }

        return false;
        }
    });


    //反馈图片
    private void showFankui(final ArrayList<String> imageList) {
        //dip转换为sp
        int wdpx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics());
        int htpx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics());

        for (int i = 0;i < imageList.size();i++) {
            View imageHolder = LayoutInflater.from(this).inflate(R.layout.item_image, null);
            ImageView thumbnail = (ImageView) imageHolder.findViewById(R.id.media_image);
            final int currentPage = i;
            thumbnail.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Intent intent = new Intent(TaskDetailActivity.this,ImagePickActivity.class);
                    intent.putStringArrayListExtra("images",imageList);
                    intent.putExtra("current",currentPage);
                    intent.putExtra("channel","task");
                    startActivity(intent);
                }
            });

            Picasso.with(this)
                    .load(imageList.get(i))
                    .placeholder(R.mipmap.ic_placehoder)
                    .into(thumbnail);

            layout_fankui.addView(imageHolder);
            thumbnail.setLayoutParams(new FrameLayout.LayoutParams(wdpx, htpx));
        }
    }


    private void httpGetTask(String taskId){
        proDialog.show();
        Map<String,String> params = new HashMap<String, String>();
        params.put("task_id",taskId);

        Log.d("task========",taskId);

        GsonRequest<TaskDetailBean> gsonRequest = new GsonRequest<TaskDetailBean>(com.android.volley.Request.Method.POST, Constans.HTTP_TASKDETAIL, TaskDetailBean.class, params, new com.android.volley.Response.Listener<TaskDetailBean>() {
            @Override
            public void onResponse(TaskDetailBean response) {

                if (response.isSuccess()){
                    Message message = new Message();
                    message.what = 0;
                    message.obj = response.getData();
                    mHandler.sendMessage(message);
                }else {
                    proDialog.dismiss();

                    showToast(response.getMsg());
                }
            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                proDialog.dismiss();

                Log.d("result=====",error + "");
            }
        });

        WgzxApplication.addRequest(gsonRequest, Constans.reqTag);
    }


    //获取取消原因
    public void httpGetRizhi(String taskid){

        Map<String,String> params = new HashMap<String, String>();
        params.put("task_id",taskid);

        GsonRequest<TaskFilterBean> gsonRequest = new GsonRequest<TaskFilterBean>(com.android.volley.Request.Method.POST, Constans.HTTP_TASKLOG, TaskFilterBean.class, params, new com.android.volley.Response.Listener<TaskFilterBean>() {
            @Override
            public void onResponse(TaskFilterBean response) {

                if (response.isSuccess()){
                    Message message = new Message();
                    message.what = 2;
                    message.obj = response.getData();
                    mHandler.sendMessage(message);
                }else {


                    Log.d("fail========",response.getMsg());
//                    showToast(tv_time,response.getMsg());
                }
            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("result=====",error + "");
            }
        });

        WgzxApplication.addRequest(gsonRequest, Constans.reqTag);
    }



}
